<?php
class Admin_Model_AdvertisementMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Admin_Model_DbTable_Advertisement');
        }
        
        return $this->_dbTable;
    }
    
	public function save(Admin_Model_TableColumn_Advertisement $advertisement) {
		try {
			$data = array (
				'id'				=> $advertisement->getId(),
	        	'vi_tri'			=> $advertisement->getVi_tri(),
				'page_id' 			=> $advertisement->getPage_id(),
	        	'id_khach_hang' 	=> $advertisement->getId_khach_hang(),
				'id_goi_quang_cao'	=> $advertisement->getId_goi_quang_cao(),
	        	'uu_tien'			=> $advertisement->getUu_tien(),
				'image_url'			=> $advertisement->getImage_url(),
				'ngay_het_han'		=> $advertisement->getNgay_het_han(),
        		'mota'				=> $advertisement->getMota(),
	        	'nguoi_tao'			=> $advertisement->getNguoi_tao(),
				'ngay_tao'			=> $advertisement->getNgay_tao(),
				'nguoi_cap_nhat'	=> $advertisement->getNguoi_cap_nhat(),
				'ngay_cap_nhat'		=> $advertisement->getNgay_cap_nhat(),
				'trang_thai'		=> $advertisement->getTrang_thai(),
				'url'				=> $advertisement->getUrl()
	        );
			
	        if ($advertisement->getId() == 0) {
				unset($data['id']);
				$this->getDbTable()->insert($data);
			} else {
				$this->getDbTable()->update($data, array('id = ?' => $advertisement->getId()));
			}
		} catch (Exception $e) {
			return false;
		}
		
		return true;
	}

	public function fetchAll($query, $option) {
		if ($query === NULL) {
			$resultSet = $this->getDbTable()->fetchAll();
		} else {
			$table = $this->getDbTable();
			$select = $table->select();
			$select->from($table)->where($query);
			$resultSet = $this->getDbTable()->fetchAll($select);
		}
		
		return $this->processResultSet($resultSet->toArray(), $option);
	}
	
	public function fetch($arrParam) {
		$paginator = $arrParam['paginator'];
		$ssFilter = $arrParam['ssFilter'];
		$table = $this->getDbTable();
		
		$select = $table->select()->setIntegrityCheck(false);
		$select->from(array('qc' => 'tb_quang_cao'), '*');
		$select->joinLeft(array('adm1' => 'tb_users_admin'), 'qc.nguoi_tao=adm1.id', 'ho_ten as ten_nguoi_tao');
		$select->joinLeft(array('adm2' => 'tb_users_admin'), 'qc.nguoi_cap_nhat=adm2.id', 'ho_ten as ten_nguoi_cap_nhat');
		$select->joinLeft(array('pg' => 'tb_page'), 'qc.page_id=pg.id', 'page as page_name');
		$select->joinLeft(array('ps' => 'tb_position'), 'qc.vi_tri=ps.id', 'position as position_name');
		$select->joinLeft(array('kh' => 'tb_khach_hang'), 'qc.id_khach_hang=kh.id', 'ten_khach_hang');
		$select->joinLeft(array('gqc' => 'tb_goi_quang_cao'), 'qc.id_goi_quang_cao=gqc.id', 'ten_goi as ten_goi_quang_cao');
		
		$state = $ssFilter['state'];
		$keywords = $ssFilter['keywords'];
		$col = $ssFilter['col'];
		$order = $ssFilter['order'];
		$select->where($table->getAdapter()->quoteInto('qc.trang_thai=?', $state));
		$select->where('qc.mota LIKE ? OR ' .
					  'qc.url LIKE ? OR ' .
					  '(page IS NOT NULL AND page LIKE ?) OR ' . 
					  '(position IS NOT NULL AND position LIKE ?) OR ' .
					  '(ten_khach_hang IS NOT NULL AND ten_khach_hang LIKE ?) OR ' .
					  '(ten_goi IS NOT NULL AND ten_goi LIKE ?)', '%' . $keywords . '%');
		$select->order($col . ' ' . $order);

		$page = $paginator['currentPage'];
		$rowCount = $paginator['itemCountPerPage'];
		$start = (int) $rowCount * ($page - 1);
		
		$select->limit($rowCount, $start);
		return $this->processResultSet($table->fetchAll($select)->toArray(), 'view');
	}
	
	private function processResultSet($resultSet, $option) {
		$entries = array();
		
		if ($option == 'view') {
			foreach ($resultSet as $row) {
				$entry = new Admin_Model_TableColumn_Advertisement($row);
				$entries[] = $entry;
			}
		} else {
			foreach ($resultSet as $row) {
				$entries[] = $row;
			}
		}
		
		return $entries;
	}
	
	public function countItem($arrParam) {
		$ssFilter = $arrParam['ssFilter'];
		
		$table = $this->getDbTable();
		$select = $table->select()->setIntegrityCheck(false);
		$select->from(array('qc' => 'tb_quang_cao'), 'count(*) as totalItem');
		$select->joinLeft(array('pg' => 'tb_page'), 'qc.page_id=pg.id');
		$select->joinLeft(array('ps' => 'tb_position'), 'qc.vi_tri=ps.id');
		$select->joinLeft(array('kh' => 'tb_khach_hang'), 'qc.id_khach_hang=kh.id');
		$select->joinLeft(array('gqc' => 'tb_goi_quang_cao'), 'qc.id_goi_quang_cao=gqc.id');
		
		$state = $ssFilter['state'];
		$keywords = $ssFilter['keywords'];
		$select->where($table->getAdapter()->quoteInto('qc.trang_thai=?', $state));
		$select->where('qc.mota LIKE ? OR ' .
					  'qc.url LIKE ? OR ' .
					  '(page IS NOT NULL AND page LIKE ?) OR ' .
					  '(position IS NOT NULL AND position LIKE ?) OR ' .
					  '(ten_khach_hang IS NOT NULL AND ten_khach_hang LIKE ?) OR ' .
					  '(ten_goi IS NOT NULL AND ten_goi LIKE ?)', '%' . $keywords . '%');
		
		$resultSet = $table->fetchAll($select);
		$array = $resultSet->toArray();
		return $array[0]['totalItem'];
	}
	
	// Update trang thai ẩn|hiện
	public function deleteItems($ids, $state, $currentUser) {
		try {
			$data = array(
				'trang_thai' 		=> $state,
				'ngay_cap_nhat' 	=> date('Y-m-d H:i:s'),
				'nguoi_cap_nhat' 	=> $currentUser
			);

			if (is_array($ids)) {
				foreach ($ids as $id) {
					$data['id'] = trim($id);
					$this->getDbTable()->update($data, array('id = ?' => $id));
				}

			} else {
				$data['id'] = trim($ids);
				$this->getDbTable()->update($data, array('id = ?' => $ids));
			}

		} catch (Exception $e) {
			return false;
		}

		return true;
	}

	// Xoá du lieu trong database
	public function removeItems($id) {
		try {
			$this->getDbTable()->delete("id = $id");

		} catch (Exception $e) {
			return false;
		}

		return true;
	}

}
?>